import { loadPoint, getFinalPos } from '@/hooks/earth/utils'
import { v1 } from 'uuid'

import _ from 'lodash'

import { apiList } from '@/api/apiList'

import { default as proj4 } from 'proj4'
import TIFFImageryProvider from "tiff-imagery-provider";

// import * as shapefile from "shapefile"
// import { useResourceHelper } from '@/hooks'

class Target {
    constructor() {
        this.viewer = window.viewer
        // 添加相关图层
        this._layer = new Cesium.CustomDataSource('targetlayer')
        this.viewer.dataSources.add(this._layer)
        this.geojsonDS = ''
    }

    removeAll() {
        // 删除3dtiles
        if (_.has(this, '_tileset')) {
            viewer.scene.primitives.remove(this._tileset)
            delete this['_tileset']
        }
        // 删除图层
        this._layer.entities.removeAll()
        // remove
        //删除影像模型
        if (_.has(this, '_imageLayer')) {
            viewer.imageryLayers.remove(this._imageLayer)
            delete this['_imageLayer']
        }
        //删除geojson图层
        if (this.geojsonDS != '') {
            viewer.dataSources.remove(this.geojsonDS)
            this.geojsonDS = ''
        }
    }

    load(item) {
        // this.removeAll()
        // 模型 3dtiles 影像
        /**

    {lng: 112.82952746128707, lat: 34.79838865917642, alt: 0},
    {lng: 114.29981743816764, lat: 34.79838865917643, alt: 0},
    {lng: 114.29981743816762, lat: 33.98199126111562, alt: 0},
    {lng: 112.82952746128707, lat: 33.98199126111562, alt: 0}

    *
    */
        switch (item.type) {
            case 'obj':
                this.loadObj(item)
                break
            case 'tif':
                // TODO 需要加载wms
                //删除影像模型
                if (_.has(this, '_imageLayer')) {
                    viewer.imageryLayers.remove(this._imageLayer)
                    delete this['_imageLayer']
                }
                // this.loadTif(item)
                this.loadImage(item)
                break
            case 'shp':
                //删除geojson图层
                if (this.geojsonDS != '') {
                    viewer.dataSources.remove(this.geojsonDS)
                    this.geojsonDS = ''
                }
                console.log(6666);
                this.loadShp(item)
                break
            default:
                break
        }
    }
    loadTif(item) {
        console.log(`/api/download/symbol/${item.filename}`)
        TIFFImageryProvider.fromUrl(`/api/download/symbol/${item.filename}`).then((provider) => {
          tiflayer = viewer.imageryLayers.addImageryProvider(provider);
          viewer.flyTo(tiflayer, {
            duration: 1,
          });
        });
    }
    loadObj(item) {
        if (item.relpath.includes('.json')) {
            // 删除3dtiles
            if (_.has(this, '_tileset')) {
                viewer.scene.primitives.remove(this._tileset)
                delete this['_tileset']
            }
            this.loadTileSet(item)
        }
        if (item.relpath.includes('.gl')) {
            this.loadModel(item)
        }
    }

    loadShp(item) {
        // let epsg32654 = 'PROJCS["WGS_1984_UTM_Zone_54N",GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0],UNIT["degree",0.0174532925199433],AUTHORITY["EPSG","4326"]],PROJECTION["Transverse_Mercator"],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",141],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",500000],PARAMETER["false_northing",0],UNIT["metre",1,AUTHORITY["EPSG","9001"]],AUTHORITY["EPSG","32654"]]'

        // const epsg32651 = '+proj=utm +zone=51 +ellps=WGS84 +datum=WGS84 +units=m +no_defs';
        // const epsg4326 = '+proj=longlat +datum=WGS84 +no_defs +type=crs';

        // proj4.defs('EPSG:32651', epsg32651);
        // proj4.defs('EPSG:32654', epsg32654);
        // proj4.defs('EPSG:4326', epsg4326);

        // Cesium.GeoJsonDataSource.crsNames['urn:ogc:def:crs:EPSG::32651'] = Cesium.GeoJsonDataSource.crsNames['EPSG:32651'] = function (coordinates) {
        //   return Cesium.Cartesian3.fromDegrees(...proj4('EPSG:32651', 'EPSG:4326', coordinates), 0)
        // }
        // Cesium.GeoJsonDataSource.crsNames['urn:ogc:def:crs:EPSG::32654'] = Cesium.GeoJsonDataSource.crsNames['EPSG:32654'] = function (coordinates) {
        //   return Cesium.Cartesian3.fromDegrees(...proj4('EPSG:32654', 'EPSG:4326', coordinates), 0)
        // }

        // const {
        //     getStaticUrl
        // } = useResourceHelper()
        // console.log(shapefile);
        // console.log(getStaticUrl(item.relpath).split(".shp")[0] + '.dbf');
        // shapefile.open(getStaticUrl(item.relpath),getStaticUrl(item.relpath).split(".shp")[0] + '.dbf').then(source => {
        //   console.log(source);
        //   source.read().then(res => {

        //     console.log(res);
        //   })
        // })

        // return
        Cesium.GeoJsonDataSource.load('/mosac_line.geojson', {
            stroke: Cesium.Color.HOTPINK,
            fill: Cesium.Color.fromAlpha(Cesium.Color.RED, 0.3),
            strokeWidth: 3,
        }).then((res) => {
            this.geojsonDS = res
            viewer.dataSources.add(res)
            viewer.flyTo(res)
        })
        return
        apiList.getShpInfo({ filePath: item.filepath }).then((res) => {
            let resjson = res.result
            if (
                _.has(res.result, 'crs') &&
                res.result.crs.properties.name == null
            ) {
                let crsname = 'wkt' + _.random(0, 999999)
                proj4.defs(crsname, resjson.wkt)
                Cesium.GeoJsonDataSource.crsNames[crsname] = function (
                    coordinates,
                ) {
                    return Cesium.Cartesian3.fromDegrees(
                        ...proj4(crsname, 'EPSG:4326', coordinates),
                        0,
                    )
                }
                res.result.crs.properties.name = crsname
            }

            if (res.result?.crs?.properties?.name == 'CRS:84') {
                delete res.result['crs']
            }

            Cesium.GeoJsonDataSource.load(res.result, {
                stroke: Cesium.Color.HOTPINK,
                fill: Cesium.Color.fromAlpha(Cesium.Color.RED, 0.3),
                strokeWidth: 3,
            }).then((res) => {
                this.geojsonDS = res
                viewer.dataSources.add(res)
                // viewer.flyTo(res.entities.values)
            })
        })
    }

    loadModel(item) {
        let pos = item?.details?.geometry?.center_coording || [0, 0]
        let e = this._layer.entities.add({
            name: item.relpath,
            // 和时间轴关联
            show: true,
            position: Cesium.Cartesian3.fromDegrees(...pos),
            // 模型数据
            model: {
                id: v1(),
                name: item.relpath,
                minimumPixelSize: 128,
                maximumScale: 200000,
                uri: `/api/download/${item.relpath.replaceAll('\\', '/')}`,
                scale: 1,
            },
        })
        viewer.flyTo(e, {
            offset: new Cesium.HeadingPitchRange(0, -1.7, 2000),
            duration: 1,
        })
    }

    loadImage(item) {
        //两种方式1.直接用cesium 2.使用earthsdk 卷帘需要用
        let name = item.relpath.replaceAll('/', ':')
        // wms
        let basemapSource = new Cesium.WebMapServiceImageryProvider({
            // 这里是你的 geoserver服务点击查看图层的 url
            url: '/imgexpress/wms',
            // 这里是自定义的图层名称
            parameters: {
                service: 'WMS',
                FORMAT: 'image/png',
                version: '1.3.0',
                TRANSPARENT: true,
                LAYERS: `${name}`,
                crs: 'EPSG:4326',
                // LAYERS: "test_tif:TRIPLESAT_2_MS_L1_20201226020854_002764VI_003",
            },
        })
        this._imageLayer =
            viewer.imageryLayers.addImageryProvider(basemapSource)

        // 添加影像范围(坐标转换)
        let polgonPositions = []
        item.details.geometry.coordinates.map((positem) => {
            console.log(
                ...getFinalPos(positem, item.details.properties.spatial_ref),
            )
            polgonPositions.push(
                Cesium.Cartesian3.fromDegrees(
                    ...getFinalPos(
                        positem,
                        item.details.properties.spatial_ref,
                    ),
                ),
            )
        })

        this._layer.entities.add({
            name: '多边形',
            id: v1(),
            polygon: {
                show: true,
                hierarchy: new Cesium.PolygonHierarchy(polgonPositions),
                // height: 0,
                material: Cesium.Color.CYAN.withAlpha(0.0),
                outline: true,
                outlineColor: Cesium.Color.BLACK,
                classificationType: Cesium.ClassificationType.BOTH,
            },
            polyline: {
                positions: [...polgonPositions],
                width: 3,
                material: Cesium.Color.BLUE.withAlpha(0.5),
                clampToGround: true,
            },
        })

        //飞到影像中心点
        viewer.camera.flyTo({
            destination: Cesium.Cartesian3.fromDegrees(
                ...getFinalPos(
                    item.details.geometry.center_coording,
                    item.details.properties.spatial_ref,
                ),
                100000,
            ),
            duration: 0.8,
        })
    }

    loadImage1(item) {
        let range = [
            { lng: 112.82952746128707, lat: 34.79838865917642, alt: 0 },
            { lng: 114.29981743816764, lat: 34.79838865917643, alt: 0 },
            { lng: 114.29981743816762, lat: 33.98199126111562, alt: 0 },
            { lng: 112.82952746128707, lat: 33.98199126111562, alt: 0 },
        ]

        //两种方式1.直接用cesium 2.使用earthsdk 卷帘需要用

        let name = item.filename.split('.')[0]
        // let name = 'a';
        this.srs = 'EPSG:4326'

        apiList
            .genWmsService({ file: item.filepath, filename: item.filename })
            .then((res) => {
                // apiList.genWmsService({file: 'd:/geoserver/data/a.tif', filename: 'aaaaaaa'}).then(res =>{
                console.log(res)

                // wmts
                let basemapSource = new Cesium.WebMapTileServiceImageryProvider(
                    {
                        //  对与url  很多博客都说要进行 如下拼接
                        // 后端返回的wmts/rest/{layer}/{style}/{TileMatrixSet}/{TileMatrix}/{TileRow}/{TileCol}?format=image/png
                        // 其实不用拼接  只需要后端返回的/wtms路径即可
                        url: '/geoserver/gwc/service/wmts', //服务地址 服务地址只需要后端返回的 /WMTS   不需要给后面拼接任何东西，
                        layer: `test_tif:${name}`, //图层名称 : "pucheng:satellite"
                        style: '',
                        format: 'image/png',
                        tileMatrixSetID: this.srs, // "EPSG:900913"
                        // 地图飞入  定位的坐标  后端返回的数据
                        // rectangle: Cesium.Rectangle.fromDegrees(
                        //     +this.zb.xmin, +this.zb.ymin, +this.zb.xmax, +this.zb.ymax),
                        // 必须加  不然地图出不来
                        //之所以要在这里提出这个tileMatrixLabels参数，是因为GeoServer在缓冲切分瓦片时对每一个缩放级别的存储目录没有使用相应的数字，而使用了网格+级别的方式来命名，如“EPSG:9100913:10”表示的是使用“EPSG:9100913”网格切分的第10级瓦片。
                        tileMatrixLabels: [
                            `${this.srs}:0`,
                            `${this.srs}:1`,
                            `${this.srs}:2`,
                            `${this.srs}:3`,
                            `${this.srs}:4`,
                            `${this.srs}:5`,
                            `${this.srs}:6`,
                            `${this.srs}:7`,
                            `${this.srs}:8`,
                            `${this.srs}:9`,
                            `${this.srs}:10`,
                            `${this.srs}:11`,
                            `${this.srs}:12`,
                            `${this.srs}:13`,
                            `${this.srs}:14`,
                            `${this.srs}:15`,
                            `${this.srs}:16`,
                            `${this.srs}:17`,
                            `${this.srs}:18`,
                        ],
                        // 必须加  不然地图出不来
                        tilingScheme: new Cesium.GeographicTilingScheme({
                            //此处很重要，很重要。。。
                            numberOfLevelZeroTilesX: 2,
                            numberOfLevelZeroTilesY: 1,
                        }),
                        // tilematrixset: this.srs,
                        // maximumLevel: 18,
                    },
                )
                this._imageLayer =
                    viewer.imageryLayers.addImageryProvider(basemapSource)
            })

        // let basemapSource = new Cesium.WebMapServiceImageryProvider(
        //   {
        //     // 这里是你的 geoserver服务点击查看图层的 url
        //     url: "/geoserver/test_tif/wms",
        //     // 这里是自定义的图层名称
        //     parameters: {
        //       service: "WMS",
        //       FORMAT: "image/png",
        //       TRANSPARENT: true,
        //       LAYERS: `test_tif:${name}`,
        //       // LAYERS: "test_tif:TRIPLESAT_2_MS_L1_20201226020854_002764VI_003",
        //     },
        //   }
        // );
        // this._imageLayer = viewer.imageryLayers.addImageryProvider(basemapSource);

        // TODO: 添加 wms图层
        // var rect;
        // this._imageLayer = viewer.imageryLayers.addImageryProvider(new Cesium.UrlTemplateImageryProvider({
        //   url: item.extraInfo.data.meta.url,
        //   rectangle: rect,
        //   //minimumLevel:0,
        //   //maximumLevel:17
        // }));

        // 添加影像范围(坐标转换)
        let polgonPositions = []
        item.details.geometry.coordinates.map((positem) => {
            console.log(
                ...getFinalPos(positem, item.details.properties.spatial_ref),
            )
            polgonPositions.push(
                Cesium.Cartesian3.fromDegrees(
                    ...getFinalPos(
                        positem,
                        item.details.properties.spatial_ref,
                    ),
                ),
            )
        })

        this._layer.entities.add({
            name: '多边形',
            id: v1(),
            polygon: {
                show: true,
                hierarchy: new Cesium.PolygonHierarchy(polgonPositions),
                // height: 0,
                material: Cesium.Color.CYAN.withAlpha(0.0),
                outline: true,
                outlineColor: Cesium.Color.BLACK,
                classificationType: Cesium.ClassificationType.BOTH,
            },
            polyline: {
                positions: [...polgonPositions],
                width: 3,
                material: Cesium.Color.BLUE.withAlpha(0.5),
                clampToGround: true,
            },
        })

        //飞到影像中心点
        // viewer.camera.flyTo({
        //     destination: Cesium.Cartesian3.fromDegrees(
        //         ...getFinalPos(
        //             item.details.geometry.center_coording,
        //             item.details.properties.spatial_ref,
        //         ),
        //         100000,
        //     ),
        //     duration: 0.8,
        // })
    }

    loadTileSet(item) {
        let tilesetconfig = {
            url: `/api/download/${item.relpath.replaceAll('\\', '/')}`,
        }

        // if (item.relpath.indexOf('hengxuhe') !== -1) {
        //     tilesetconfig.modelMatrix = Cesium.Matrix4.fromArray([
        //         0.6455158870444668, 0.304245991893278, -0.7005309529136243, 0,
        //         0.2703959670340135, -0.9488612092415243, -0.16293687921539857,
        //         0, -0.7142795395256232, -0.08424240033135338,
        //         -0.6947718743598333, 0, 296876.23525132285, 8092512.769083748,
        //         3976065.9774999563, 1,
        //     ])
        // }

        var tileset = viewer.scene.primitives.add(
            new Cesium.Cesium3DTileset(tilesetconfig),
        )
        // viewer.flyTo(tileset)
        this._tileset = tileset
    }

    loadPort(item) {
        var tileset = viewer.scene.primitives.add(
            new Cesium.Cesium3DTileset({
                url: item.extraInfo.data.meta.url,
                modelMatrix: Cesium.Matrix4.fromArray(
                    item.extraInfo.data.meta.modelMatrix,
                ),
            }),
        )
        viewer.flyTo(tileset)
        this._tileset = tileset
    }
}

// export {move}
export default Target
